//
//  EditViewController.m
//  qunfa
//
//  Created by Admin on 2017/8/11.
//  Copyright © 2017年 cuixiaocun. All rights reserved.
//

#import "EditViewController.h"
#import "MOFSPickerManager.h"
@interface EditViewController ()<UITextFieldDelegate,UITextViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    NSString *isLeveler;//yes==文字 no==图片
    UITextField *titleTF;
    UITextView *detailTV;
    UILabel *plabel;
    UIButton *upLoadBtn;
    UIButton *xBtn;
    UIView *centerView;
    UIView *bottomView;
    UIView *topView;
    UIImage *imgToFWD;
    UITextField *numberTF;
    UIButton* isPushBtn;
}
@end

@implementation EditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:BGColor];
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    isLeveler =@"NO";
    //替代导航栏的imageview
    UIImageView *topImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, CXCWidth, 64)];
    topImageView.userInteractionEnabled = YES;
    topImageView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:topImageView];
    
    //添加返回按钮
    UIButton *  returnBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    returnBtn.frame = CGRectMake(0, 20, 44, 44);
    [returnBtn setImage:[UIImage imageNamed:navBackarrow] forState:UIControlStateNormal];
    [returnBtn addTarget:self action:@selector(returnBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [topImageView addSubview:returnBtn];
    
    UIImageView*bgImg =[[UIImageView alloc]init];
    bgImg.backgroundColor=NavColor;
    [topImageView addSubview:bgImg];
    bgImg.userInteractionEnabled = YES;
    bgImg.layer.cornerRadius=2;
    [bgImg setFrame:CGRectMake(183*Width, 20+(44-56*Width)/2-1, 384*Width, 60*Width)];
    //会员
    UIButton *hyBtn =[[UIButton alloc]initWithFrame:CGRectMake(2*Width, 2*Width, 190*Width, 56*Width)];
    [hyBtn setBackgroundColor:NavColor];
    hyBtn.selected=YES;
    
    if (hyBtn.selected==YES) {
        [hyBtn setBackgroundColor:NavColor];
    }else
    {
        [hyBtn setBackgroundColor:[UIColor whiteColor]];
    }
    [hyBtn setTitleColor:NavColor forState:UIControlStateNormal];
    [hyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [hyBtn setTitle:@"文字信息" forState:UIControlStateNormal];
    [hyBtn setTitle:@"文字信息" forState:UIControlStateSelected];
    hyBtn.tag =120;
    hyBtn.titleLabel.font =[UIFont systemFontOfSize:15];
    //    hyBtn.layer.cornerRadius=4;
    [hyBtn addTarget:self action:@selector(login:) forControlEvents:UIControlEventTouchUpInside];
    [bgImg addSubview:hyBtn];
    
    //代理
    UIButton *dlBtn =[[UIButton alloc]initWithFrame:CGRectMake(hyBtn.right,2*Width, 190*Width, 56*Width)];
    [dlBtn setBackgroundColor:NavColor];
    dlBtn.selected=NO;
    //    dlBtn.layer.cornerRadius=4;
    if (dlBtn.selected==YES) {
        [dlBtn setBackgroundColor:NavColor];
    }else
    {
        [dlBtn setBackgroundColor:[UIColor whiteColor]];
    }
    dlBtn.titleLabel.font =[UIFont systemFontOfSize:15];
    [dlBtn setTitle:@"图文信息" forState:UIControlStateNormal];
    [dlBtn setTitle:@"图文信息" forState:UIControlStateSelected];
    [dlBtn setTitleColor:NavColor forState:UIControlStateNormal];
    [dlBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [topImageView addSubview:dlBtn];
    dlBtn.tag =121;
    [dlBtn addTarget:self action:@selector(login:) forControlEvents:UIControlEventTouchUpInside];
    
    [bgImg addSubview:dlBtn];
    [self  mainView];
}
- (void)mainView
{
    //底部scrollview
    TPKeyboardAvoidingScrollView *bgScrollView =[[TPKeyboardAvoidingScrollView alloc] initWithFrame:CGRectMake(0, 64+20*Width,CXCWidth, CXCHeight-64-20*Width )];
    [bgScrollView setUserInteractionEnabled:YES];
    [bgScrollView setBackgroundColor:BGColor];
    [self.view addSubview:bgScrollView];
    bgScrollView.showsVerticalScrollIndicator =NO;
    
    
    topView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, CXCWidth,310*Width )];
    topView.backgroundColor =[UIColor whiteColor];
    [bgScrollView addSubview:topView];
    
    titleTF = [[UITextField alloc] init];
    [titleTF setTag:20];
    [titleTF setPlaceholder:@"信息标题(不在发送范围内,限制6个字)"];
    [titleTF setDelegate:self];
    [titleTF setFont:[UIFont systemFontOfSize:14]];
    [titleTF setTextColor:[UIColor blackColor]];
    [titleTF setFrame:CGRectMake(30*Width, 0,680*Width,100*Width)];
    [titleTF setClearButtonMode:UITextFieldViewModeWhileEditing];
    [topView addSubview:titleTF];
    
    //横线
    UIImageView*xian =[[UIImageView alloc]init];
    xian.backgroundColor =BGColor;
    [topView addSubview:xian];
    xian.frame =CGRectMake(20*Width,98.5*Width, CXCWidth, 1.5*Width);
    detailTV =[[UITextView alloc]initWithFrame:CGRectMake(30*Width, xian.bottom,680*Width,180*Width)];
    
    [detailTV setFont:[UIFont systemFontOfSize:14]];
    detailTV.delegate  = self;
    
    [topView addSubview:detailTV];
    
    plabel =[[UILabel alloc]initWithFrame:CGRectMake( detailTV.left+4*Width  ,detailTV.top+4*Width ,600*Width , 40*Width)];
    plabel.text = @"填写您要推广的内容";
    plabel.textColor  = [UIColor lightGrayColor];
    plabel.font = [UIFont systemFontOfSize:14];
    plabel.enabled = NO;//lable必须设置为不可用
    plabel.backgroundColor = [UIColor clearColor];
    [topView addSubview:plabel];
    
    centerView =[[UIView alloc]initWithFrame:CGRectMake(0*Width, topView.bottom, CXCWidth, 190*Width)];
    centerView.backgroundColor =[UIColor whiteColor];
    [bgScrollView addSubview:centerView];
    
    upLoadBtn= [[UIButton alloc]initWithFrame:CGRectMake(30*Width, 30*Width, 130*Width, 130*Width)];
    [upLoadBtn setBackgroundImage:[UIImage imageNamed:@"icon_addpic"] forState:UIControlStateNormal];
    upLoadBtn.selected   =NO;
    [upLoadBtn addTarget:self action:@selector(photoUpLoad) forControlEvents:UIControlEventTouchUpInside];
    [centerView   addSubview:upLoadBtn];

    xBtn = [[UIButton alloc]initWithFrame:CGRectMake(140*Width, 30*Width, 30*Width, 30*Width)];
    [xBtn setImage:[UIImage imageNamed:@"icon_close_corner"] forState:UIControlStateNormal];
    [xBtn addTarget:self action:@selector(delete) forControlEvents:UIControlEventTouchUpInside];
    [centerView   addSubview:xBtn];
    centerView.hidden =YES;
    xBtn.hidden =YES;
    

    bottomView =[[UIView alloc]initWithFrame:CGRectMake(0*Width, topView.bottom+0*Width, CXCWidth, 190*Width)];
    bottomView.backgroundColor =BGColor;
    [bgScrollView addSubview:bottomView];
     NSArray*leftArr =@[@"推广人数",@"推广地区",@"推广性别",@"推广选项",@"开启推送",@"",@"",@"",] ;
    NSArray*leftImgArr =@[@"icon_renshu",@"icon_diqu",@"icon_sex",@"icon_xuanxiang",@"",] ;
    NSArray*rightArr =@[@"填写人数(0表示全部好友)",@"全部",@"全部",@"全部",@"",@"",@"",@"",] ;

    for (int i=0; i<5; i++) {
        UIView *bgview =[[UIView alloc]init];
        bgview.backgroundColor =[UIColor whiteColor];
        
        UILabel* leftLabe = [[UILabel alloc]initWithFrame:CGRectMake(100*Width,20*Width ,200*Width , 40*Width)];
        leftLabe.text = leftArr[i];
        leftLabe.font = [UIFont systemFontOfSize:15];
        leftLabe.textColor = BlackColor;
        [bgview addSubview:leftLabe];

        if (i==4) {
            bgview.frame =CGRectMake(0,40*Width+100*i*Width, CXCWidth, 100*Width);
            leftLabe.frame = CGRectMake(32*Width,20*Width ,200*Width , 40*Width);

        }else
        {
            //左图片
            UIImageView  *jiantou =[[UIImageView alloc]initWithFrame:CGRectMake(32*Width,20*Width ,40*Width , 40*Width)];
            [bgview addSubview:jiantou];
            [jiantou setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@",leftImgArr[i]]]];
            bgview.frame =CGRectMake(0, 20*Width+100*i*Width, CXCWidth, 100*Width);

        }
        [bottomView addSubview:bgview];
       
        if (i==0) {
            //右边
            UITextField *inputText = [[UITextField alloc] init];
            [inputText setTag:i+70];
            [inputText setDelegate:self];
            inputText.placeholder =rightArr[i];
            inputText.keyboardType =UIKeyboardTypeNumberPad;
            [inputText setFont:[UIFont systemFontOfSize:16]];
            [inputText setTextColor:[UIColor blackColor]];
            [inputText setFrame:CGRectMake(200*Width, 0,520*Width,99*Width)];
            inputText.textAlignment =NSTextAlignmentRight;

            [inputText setClearButtonMode:UITextFieldViewModeWhileEditing];
            [bgview addSubview:inputText];
            numberTF =inputText;
        }
        if (i>0&&i<4) {
            UIButton* deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            deleteBtn.frame = CGRectMake(300*Width, 0*Width, 450*Width, 99*Width);
            [deleteBtn addTarget:self action:@selector(choose:) forControlEvents:UIControlEventTouchUpInside];
            deleteBtn.tag = 90+i;
            [bgview addSubview:deleteBtn];
            
            UILabel*rightLabel  =[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 350*Width, 99*Width)];
            rightLabel.text = rightArr[i];
            rightLabel.font = [UIFont systemFontOfSize:15];
            rightLabel.textColor = BlackColor;
            rightLabel.tag =40+i;
            rightLabel.textAlignment =NSTextAlignmentRight;
            [deleteBtn addSubview:rightLabel];

            //箭头
            UIImageView  *jiantou =[[UIImageView alloc]initWithFrame:CGRectMake(680*Width, 35*Width,30*Width , 30*Width)];
            [bgview addSubview:jiantou];
            [jiantou setImage:[UIImage imageNamed:@"register_btn_nextPage"]];
        }
        if(i==4)
        {
            UIButton* deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            deleteBtn.frame = CGRectMake(650*Width, 0*Width, 99*Width, 99*Width);
            [deleteBtn setImage:[UIImage imageNamed:@"adress_btn_radio_sel"] forState:UIControlStateSelected];
            [deleteBtn setImage:[UIImage imageNamed:@"adress_btn_radio"] forState:UIControlStateNormal];
            [deleteBtn addTarget:self action:@selector(choosePush:) forControlEvents:UIControlEventTouchUpInside];
            deleteBtn.tag = 90+i;
            [bgview addSubview:deleteBtn];
            isPushBtn =deleteBtn;
        }
    
        //横线
        UIImageView*xian =[[UIImageView alloc]init];
        xian.backgroundColor =BGColor;
        [bgview addSubview:xian];
        xian.frame =CGRectMake(0,98.5*Width, CXCWidth, 1.5*Width);
        

    }
    
    UILabel *mianzeLabel =[[UILabel alloc]initWithFrame:CGRectMake(30*Width, 560*Width,690*Width ,350*Width )];
    mianzeLabel.text = @"免责声明：\n1、分享平台会员可自行张贴其商业信息，包括文字描述、图片或照片说明。分享平台不对上述信息的真实性、准确性或及时性、完整性负责。\n2、用户同意自行承担由于使用分享平台服务所获知信息而产生的全部商业风险，分享平台及其组织机构不承担任何责任。\n3、分享平台不为任何会员发布的内容负责，包括但不限于任何内容和任何错误或遗漏而衍生之任何损失或损害。";
    mianzeLabel.font = [UIFont systemFontOfSize:12];
    mianzeLabel.textColor = BlackColor;
    mianzeLabel.numberOfLines =0;
    mianzeLabel.backgroundColor =BGColor;
    [bottomView addSubview:mianzeLabel];
    bottomView.height  =mianzeLabel.height+560*Width;
//    [bgScrollView setContentSize:CGSizeMake(CXCWidth,mianzeLabel.bottom )];
    
    [bgScrollView setContentSize:CGSizeMake(CXCWidth,1600*Width)];

    UIView *foodView =[[UIView alloc]initWithFrame:CGRectMake(0, CXCHeight-128*Width, CXCWidth, 128*Width)];
    foodView.backgroundColor =[UIColor whiteColor];
    [self.view addSubview:foodView];
    
    UIButton *addAddressBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addAddressBtn setFrame:CGRectMake(40*Width,20*Width , 670*Width, 88*Width)];
    [addAddressBtn setBackgroundColor:NavColor];
    [addAddressBtn.layer setCornerRadius:4];
    [addAddressBtn.layer setMasksToBounds:YES];
    
    [addAddressBtn setTitle:@"保存" forState:UIControlStateNormal];
    [addAddressBtn.titleLabel setTextColor:[UIColor whiteColor]];
    [addAddressBtn.titleLabel setFont:[UIFont boldSystemFontOfSize:18]];
    [addAddressBtn addTarget:self action:@selector(addAddressBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [foodView addSubview:addAddressBtn];
    //横线
    UIImageView*xian2 =[[UIImageView alloc]init];
    xian2.backgroundColor =BGColor;
    [foodView addSubview:xian2];
    xian2.frame =CGRectMake(0,0, CXCWidth, 1.5*Width);
    if (_dic) {
        if ([[_dic objectForKey:@"type"]isEqualToString:@"1"]) {//文字
            UIButton *btn =[self.view viewWithTag:120];
            
            [self login:btn];
        }else if([[_dic objectForKey:@"type"]isEqualToString:@"2"])//图片+文字
        {
            UIButton *btn =[self.view viewWithTag:121];
            [self login:btn];
        }
        //标题、内容、人数
        titleTF.text =[NSString stringWithFormat:@"%@",[_dic objectForKey:@"title"]];
        detailTV.text =[NSString stringWithFormat:@"%@",[_dic objectForKey:@"content"]];
        plabel.hidden =YES;
        
        numberTF.text =[NSString stringWithFormat:@"%@",[_dic objectForKey:@"num"]];
        UILabel *addressLabel =[self.view viewWithTag:41];
        UILabel *sexLabel =[self.view viewWithTag:42];
        UILabel *friendLabel =[self.view viewWithTag:43];
        //地区
        if(!([[_dic objectForKey:@"region"]isEqual:[NSNull null]]||[[_dic objectForKey:@"region"]isEqualToString:@"<null>"]||[[_dic objectForKey:@"region"]isEqualToString:@""])){
            addressLabel.text =[NSString stringWithFormat:@"%@",[_dic objectForKey:@"region"]];
            
        }else
        {
            addressLabel.text =@"全部";

        }
        //性别
        if(!([[_dic objectForKey:@"sex"]isEqual:[NSNull null]]||[[_dic objectForKey:@"sex"]isEqualToString:@"<null>"])){
            sexLabel.text =[NSString stringWithFormat:@"%@",[_dic objectForKey:@"sex"]];
            
        }else
        {
            sexLabel.text =@"全部";
            
        }
        //推广范围
        if(!([[_dic objectForKey:@"option"]isEqual:[NSNull null]]||[[_dic objectForKey:@"option"]isEqualToString:@"<null>"])){
            friendLabel.text =[NSString stringWithFormat:@"%@",[_dic objectForKey:@"option"]];
            
        }else
        {
            friendLabel.text =@"全部";
        }
        //是否推送
        if(([[_dic objectForKey:@"ispush"]isEqual:[NSNull null]]||[[_dic objectForKey:@"ispush"]isEqualToString:@"<null>"])){

            
        }else
        {
            if ([[_dic objectForKey:@"ispush"]isEqualToString:@"1"]) {
                
                isPushBtn.selected =YES;
            }else
            {
                isPushBtn.selected =NO;

            }
        }
        //图片
        if (!([[_dic objectForKey:@"img"]isEqual:[NSNull null]]||[[_dic objectForKey:@"img"]isEqualToString:@"<null>"]||[[_dic objectForKey:@"img"]isEqualToString:@""])) {
            xBtn.hidden=YES;
            centerView.hidden =NO;
            if([[_dic objectForKey:@"type"]isEqualToString:@"2"])
            {
                imgToFWD  =[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[_dic objectForKey:@"img"]]]]];
                xBtn.hidden=NO;

                [upLoadBtn setBackgroundImage:imgToFWD forState:UIControlStateNormal];

            
            }
                   }


    }

    
    
}
- (void)choosePush:(UIButton *)btn
{
    btn.selected =!btn.selected;

}
- (void)delete
{
    upLoadBtn.selected=NO;
    xBtn.hidden  =YES;
    imgToFWD =nil;
    [upLoadBtn setBackgroundImage:[UIImage imageNamed:@"icon_addpic"] forState:UIControlStateNormal];

    

}

- (void)choose:(UIButton*)btn
{
    [titleTF resignFirstResponder];
    [detailTV resignFirstResponder];
    [numberTF resignFirstResponder];
    
    if(btn.tag ==91)
    {
        UILabel *addLabel =[self.view viewWithTag:41];
        [[MOFSPickerManager shareManger] showMOFSAddressPickerWithDefaultAddress:nil numberOfComponents:2 title:@"选择地址" cancelTitle:@"取消" commitTitle:@"确定" commitBlock:^(NSString *address, NSString *zipcode) {
            NSString *str2=address;
            NSArray *temp=[str2 componentsSeparatedByString:@"-"];
            if ([temp[1]isEqualToString:@"全部"]) {
                addLabel.text = temp[0];

            }else
            {
                addLabel.text = [address stringByReplacingOccurrencesOfString:@"-" withString:@"/"];

            
            }
            NSLog(@"%@",[temp description]);

        } cancelBlock:^{
            addLabel.text =@"全部";
            
        }];

    
    }
    if(btn.tag ==92)
    {
        UILabel *addLabel =[self.view viewWithTag:42];

        NSArray *arr =@[@"男",@"女",@"全部"];
        //选择银行
        SRActionSheet *actionSheet = [SRActionSheet sr_actionSheetViewWithTitle:@"选择性别" cancelTitle:@"取消" destructiveTitle:nil withNumber:@"4" withLineNumber:@"1" otherTitles:arr otherImages:nil selectActionBlock:^(SRActionSheet *actionSheet, NSInteger index) {
            if (index<0||index>arr.count-1) {
                return;
            }
            addLabel.text =[NSString stringWithFormat:@"%@",arr[index]];
            NSLog(@"%zd----%@", index,addLabel.text);
        
         }];
    
    
        [actionSheet show];
        

    }
    if(btn.tag ==93)
    {
        UILabel *addLabel =[self.view viewWithTag:43];
        
        NSArray *arr =@[@"好友",@"群组",@"全部"];
        //选择银行
        SRActionSheet *actionSheet = [SRActionSheet sr_actionSheetViewWithTitle:@"选择推广范围" cancelTitle:@"取消" destructiveTitle:nil withNumber:@"4" withLineNumber:@"1" otherTitles:arr otherImages:nil selectActionBlock:^(SRActionSheet *actionSheet, NSInteger index) {
            if (index<0||index>arr.count-1) {
                return;
            }
            addLabel.text =[NSString stringWithFormat:@"%@",arr[index]];
            NSLog(@"%zd----%@", index,addLabel.text);
            
        }];
        
        
        [actionSheet show];

    }
}


- (void)login:(UIButton *)btn//判断是文字还是图片
{
    for (int i=0; i<2; i++) {
        UIButton *btnAll =[self.view viewWithTag:120+i];
        btnAll.selected =NO;
        [btnAll setBackgroundColor:[UIColor whiteColor]];
    }
    [btn setBackgroundColor:NavColor];
    btn.selected =YES;
    centerView.hidden =NO;

    if(btn.tag==120)
    {
        isLeveler=@"NO";//文字
        centerView.hidden =YES;
        bottomView.top =topView.bottom;
    }else
    {
        isLeveler=@"YES";//图片
        centerView.hidden =NO;
        bottomView.top =centerView.bottom;
    }
    
}
- (void)addAddressBtnAction
{
    if ([isLeveler isEqualToString:@"NO"]) {//文字
        [self  editToFWQ:@""];

    }else if([isLeveler isEqualToString:@"YES"])//图片
    {
        [self photoUpLoadToFWQ ];
    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)returnBtnAction
{

    [self.navigationController popViewControllerAnimated:YES];
    

}
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    [plabel setAlpha:0];
    return YES;
}
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    NSInteger strLength = textView.text.length - range.length + text.length;
    if (strLength==0) {
        [plabel setAlpha:1];
        
    }else{
        [plabel setAlpha:0];
        
    }
    if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车，即按下return
        //在这里做你响应return键的代码
        [textView resignFirstResponder];
        return NO; //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行
    }
    
    return YES;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [detailTV resignFirstResponder];
    
}
- (void)photoUpLoad
{
    if (IOS7)
    {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"获取图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        //判断是否支持相机，模拟器没有相机
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
                                            {
                                                //相机
                                                UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
                                                imagePickerController.delegate = self;
                                                imagePickerController.allowsEditing = YES;
                                                imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                                                [self presentViewController:imagePickerController animated:YES completion:^{}];
                                            }];
            [alertController addAction:defaultAction];
        }
        UIAlertAction *defaultAction1 = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //相册
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.delegate = self;
            imagePickerController.allowsEditing = YES;
            imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:imagePickerController animated:YES completion:^{
                imagePickerController.delegate = self;
            }];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action)
                                       {
                                       }];
        
        [alertController addAction:cancelAction];
        [alertController addAction:defaultAction1];
        //弹出试图，使用UIViewController的方法
        [self presentViewController:alertController animated:YES completion:nil];
    }
    else
    {
        UIActionSheet *sheet;
        //判断是否支持相机，模拟器没有相机
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            sheet = [[UIActionSheet alloc] initWithTitle:@"获取图片" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"拍照",@"从相册选择", nil];
        }
        else
        {
            sheet = [[UIActionSheet alloc] initWithTitle:@"获取图片" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"从相册选择", nil];
        }
        [sheet showInView:self.view];
    }
    
}
-(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSInteger sourctType = 0;
    //判断是否支持相机
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        switch (buttonIndex) {
            case 1:
                sourctType = UIImagePickerControllerSourceTypeCamera;
                break;
            case 2:
                sourctType = UIImagePickerControllerSourceTypePhotoLibrary;
                break;
            default:
                break;
        }
    }
    else
    {
        if (buttonIndex == 1)
        {
            sourctType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        }
    }
    //跳转到相机或者相册页面
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = sourctType;
    [self presentViewController:imagePickerController animated:YES completion:nil];
    
    
}
//IOS7以上的都要调用方法，选择完成后调用该方法
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    // 把头像图片存到本地
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"Img.png"]];// 保存文件的名称
    NSData *imageData = UIImageJPEGRepresentation(image, 0.1);
    [imageData writeToFile:filePath atomically:YES];
    
    UIImage *img =[[UIImage alloc] initWithContentsOfFile:filePath];
    UIImage *savedImage =[self image:img rotation:(img.imageOrientation) ] ;
    upLoadBtn.selected   =YES;
    xBtn.hidden  =NO;

    [upLoadBtn setBackgroundImage:savedImage forState:UIControlStateNormal];
    
    imgToFWD =savedImage;
    
}
- (UIImage *)image:(UIImage *)image rotation:(UIImageOrientation)orientation
{
    
    long double rotate = 0.0;
    CGRect rect;
    float translateX = 0;
    float translateY = 0;
    float scaleX = 1.0;
    float scaleY = 1.0;
    
    switch (orientation) {
        case UIImageOrientationLeft:
            rotate = M_PI_2;
            rect = CGRectMake(0, 0, image.size.height, image.size.width);
            translateX = 0;
            translateY = -rect.size.width;
            scaleY = rect.size.width/rect.size.height;
            scaleX = rect.size.height/rect.size.width;
            break;
        case UIImageOrientationRight:
            rotate = 3 * M_PI_2;
            rect = CGRectMake(0, 0, image.size.height, image.size.width);
            translateX = -rect.size.height;
            translateY = 0;
            scaleY = rect.size.width/rect.size.height;
            scaleX = rect.size.height/rect.size.width;
            break;
        case UIImageOrientationDown:
            rotate = M_PI;
            rect = CGRectMake(0, 0, image.size.width, image.size.height);
            translateX = -rect.size.width;
            translateY = -rect.size.height;
            break;
        default:
            rotate = 0.0;
            rect = CGRectMake(0, 0, image.size.width, image.size.height);
            translateX = 0;
            translateY = 0;
            break;
    }
    
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    //做CTM变换
    CGContextTranslateCTM(context, 0.0, rect.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextRotateCTM(context, rotate);
    CGContextTranslateCTM(context, translateX, translateY);
    
    CGContextScaleCTM(context, scaleX, scaleY);
    //绘制图片
    CGContextDrawImage(context, CGRectMake(0, 0, rect.size.width, rect.size.height), image.CGImage);
    
    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
    
    return newPic;
}
- (void)photoUpLoadToFWQ
{
    if (imgToFWD==nil) {
        [MBProgressHUD  showError:@"请上传图片或选择文字信息" ToView:self.view];
        return;
    }
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"html/text",@"text/json", @"text/html", @"text/plain",nil];
    NSString *url=[NSString stringWithFormat:@"%@/%@",SERVERURL,@"index.php/Home/Login/upidcard"];
    
    [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *imageData = UIImageJPEGRepresentation(imgToFWD, 0.5);
        //使用日期生成图片名称
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
        [formData appendPartWithFileData :imageData name :@"upimg" fileName : fileName mimeType : @"image/jpg/png/jpeg" ];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        
        NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"图片请求成功JSON:%@", JSON);
        if ([ [NSString stringWithFormat:@"%@",[JSON objectForKey:@"code"]]isEqualToString:@"0"])
        {
            NSString *addressStr =[NSString stringWithFormat:@"%@",[[JSON objectForKey:@"data"] objectForKey:@"url"]];
            
            [self  editToFWQ:addressStr];
            
        }else
        {
            [ProgressHUD dismiss];
            [MBProgressHUD showError:[NSString stringWithFormat:@"%@",[JSON objectForKey:@"msg"]] ToView:self.view];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:@"加载出错" ToView:self.view];
        NSLog(@"请求失败:%@", error.description);
    }];
    
    
    
}
- (void)editToFWQ:(NSString*)address
{
    NSString *logintype =@"1";
    if([isLeveler isEqualToString:@"NO"])//文字
    {
    logintype =@"1";
    }else//NO图片+文字
    {
    logintype =@"2";
    }
    
    UILabel *addressLabel =[self.view viewWithTag:41];
    UILabel *sexLabel =[self.view viewWithTag:42];
    UILabel *friendLabel =[self.view viewWithTag:43];
    NSString *sexString=0;
    if ([sexLabel.text isEqualToString:@"男"]) {
        sexString =@"1";
    }else if ([sexLabel.text isEqualToString:@"女"]) {
        sexString =@"2";
    }else  if ([sexLabel.text isEqualToString:@"全部"]) {
        sexString =@"0";
    }
    NSString *friendString=@"";
    if ([friendLabel.text isEqualToString:@"好友"]) {
        friendString =@"1";
    }else if ([friendLabel.text isEqualToString:@"群组"]) {
        friendString =@"2";
    }else  if ([friendLabel.text isEqualToString:@"全部"]) {
        friendString =@"3";
    }
    
    NSString *isPushString=0;
    if (isPushBtn.selected==YES) {
        isPushString =@"1";
    }else if (isPushBtn.selected==NO) {
        isPushString =@"2";
    }
    
    
    NSMutableDictionary *dic1 = [NSMutableDictionary dictionary];
    [dic1 setDictionary:@{
                          @"memberId":[NSString stringWithFormat:@"%@",[[PublicMethod getDataKey:member] objectForKey:@"id"]],
                          @"logintype":logintype,
                          @"title":titleTF.text,
                          @"content":[NSString stringWithFormat:@"%@",detailTV.text],
                          @"num":[NSString stringWithFormat:@"%@",numberTF.text],
                          @"city":[NSString stringWithFormat:@"%@",addressLabel.text],
                          @"sex":[NSString stringWithFormat:@"%@",sexString],
                          @"option":[NSString stringWithFormat:@"%@",friendString],
                          @"isPush":[NSString stringWithFormat:@"%@",isPushString],
                          @"img":address,
                          }];
    if(_dic)
    {
        [dic1 setObject:[NSString stringWithFormat:@"%@",[_dic objectForKey:@"id"]] forKey:@"id"];
        
    }
    NSLog(@"%@",dic1);
//    urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"html/text",@"text/json", @"text/html", @"text/plain",nil];
    NSString *url;

    if (_dic) {
        url =[NSString stringWithFormat:@"%@/%@",SERVERURL,@"index.php/Home/Advert/editAdvert"];
 
    }else
    {
       url =[NSString stringWithFormat:@"%@/%@",SERVERURL,@"index.php/Home/Advert/addAdvert"];

    }
    //    NSDictionary *dic = [PublicMethod ASCIIwithDic:dic1];//当加密的时候用
    NSMutableDictionary*parameter =[NSMutableDictionary dictionary];
    int num = (arc4random() % 10000);
    NSString*  randomNumber = [NSString stringWithFormat:@"%.4d", num];
    NSLog(@"%@", randomNumber);
    
    [parameter setDictionary:dic1];
    [manager POST:url parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        
        NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"上传成功JSON:%@", JSON);
        if ([ [NSString stringWithFormat:@"%@",[JSON objectForKey:@"code"]]isEqualToString:@"0"])
        {
            [self.navigationController popViewControllerAnimated:YES];
            [self.delegate needReloadDataEdit];
        }else
        {
            [ProgressHUD dismiss];
            [MBProgressHUD showError:[NSString stringWithFormat:@"%@",[JSON objectForKey:@"msg"]] ToView:self.view];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:@"加载出错" ToView:self.view];
        NSLog(@"请求失败:%@", error.description);
    }];
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
